package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import model.Database;

/**
 * Is the panel representing the production of a Pallet.
 */
public class ProducePanel extends JPanel implements ActionListener{

	private MessageLabel message;
	private JTextField date;
	private JButton produceButton;
	private JComboBox cookies;
	private Database db;
	
	/**
	 * The constructor of the ProducePanel and creates the Panel.
	 * @param db is the access to the database.
	 */
	public ProducePanel(Database db){
		this.db = db;
		setLayout(new BorderLayout());
		JPanel north = new JPanel(new GridLayout(2,1));
		JPanel produce = new JPanel(new GridLayout(1,3));
		cookies = new JComboBox(db.getCookieNames());
		date = new JTextField(Database.getDate());
		produceButton = new JButton("Produce");
		produceButton.addActionListener(this);
		produce.add(cookies);
		produce.add(date);
		produce.add(produceButton);
		message = new MessageLabel("Click produce to produce a pallet of selected cookies on given date!");
		north.add(produce);
		north.add(message);
		add(north, BorderLayout.NORTH);
		
	}
	
	/**
	 * Sets the cookies which can be selected.
	 * @param cookieNames is a list of all cookies that can be selected.
	 */
	public void setCookies(String[] cookieNames){
		cookies.removeAllItems();
		for(String s : cookieNames){
			cookies.addItem(s);
		}
	}

	/**
	 * The method which produce the pallet and creates messages to the user as what happened.
	 * @param event is the event which fired the event.
	 */
	public void actionPerformed(ActionEvent event) {
		String d = date.getText();
		try{
			Date p = Date.valueOf(d);
		}catch(Exception e){
			message.setMessage("The date needs to follow the date format: YYYY-MM-DD",true);
			return;
		}
		String c = null;
		if(cookies.getSelectedItem()==null){
			message.setMessage("A cookie need to be selected!",true);
			return;
		}else{
			c = cookies.getSelectedItem().toString();
		}
		ArrayList<String> missingIngredients = db.producePallet(c, d);
		if(missingIngredients==null){
			message.setMessage("A database error occured!",true);
		}else if(!missingIngredients.isEmpty()){
			String text = "";
			for(int i = 0;i<missingIngredients.size();i++){
				text+=missingIngredients.get(i);
				if(i<missingIngredients.size()-1){
					text+=", ";
				}
			}
			message.setMessage("Not enough stored of "+text,true);
		}else{
			message.setMessage("Pallet with "+c+"s has successfully been created!",false);
		}
		
	}
	
}
